package com.my.gis.config.postgis;

import net.postgis.jdbc.PGgeometry;
import net.postgis.jdbc.geometry.Geometry;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * 〈功能简述〉<br>
 * 〈PgGeometryTypeHandler实现通用的geometry类型转net.postgis.jdbc.geometry.Geometry;及其实现类〉
 *
 * @author Mr.QL
 * @ClassName JtsGeometryTypeHandler
 * @Date 2021-12-10 16:58
 * @Version 1.0
 */
@SuppressWarnings("unchecked")
@MappedTypes(Geometry.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class PgGeometryTypeHandler extends BaseTypeHandler<Geometry> {

    public PgGeometryTypeHandler() {

    }

    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        PGgeometry pGgeometry = new PGgeometry(parameter);
        ps.setObject(i, pGgeometry);
    }

    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        PGgeometry pGgeometry = (PGgeometry) rs.getObject(columnName);
        if (pGgeometry == null) {
            return null;
        }
        return pGgeometry.getGeometry();
    }

    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        PGgeometry pGgeometry = (PGgeometry) rs.getObject(columnIndex);
        if (pGgeometry == null) {
            return null;
        }
        return pGgeometry.getGeometry();
    }

    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        PGgeometry pGgeometry = (PGgeometry) cs.getObject(columnIndex);
        if (pGgeometry == null) {
            return null;
        }
        return pGgeometry.getGeometry();
    }
}
